#include "approveexam.h"
#include"../utils/database.h"
#include"userdao.h"
#include"windowdao.h"
#include"saledao.h"
#include<QDebug>
#include<QSqlError>
/*
 * 所有审批的数据库操作 实现，具体包括：
 * 1）窗口审批，
 * 2）加盟审批，商家申请加入组织
 * 3）菜品审批，商家申请创建新的菜品
 * 4）优惠信息审批，
 *
 * edit by cheney
 * */

ApproveExam::ApproveExam()
{
    result=QSqlQuery(*DataBase::getInstance());
}


//查询某个组织下的所有待审批的窗口，一个窗口对应一个用户的审批
bool ApproveExam::selectOrgExamWindow(OrganizationInfo org,vector<WindowInfo>& wins,vector<User>& users,vector<int>& exam_ids)
{
    QString sql="select t1.id win_id,t2.phone phone,t3.id exam_id  "
                "from WindowInfo t1, User t2, windowApproval t3  "
                "where t1.id = t3.window_id and t2.phone = t3.user_id and t1.organization_id = %1 and t3.status ='%2';";
    sql=sql.arg(org.id).arg(ApproveExam::STATUS_EXAM);

    result.clear();
    bool re=result.exec(sql);
    if(!re)
    {
      qDebug()<<result.lastError().text();
    }
    UserDao ud;
    WindowDao wd;

    while (result.next()) {
        User user;
        WindowInfo win;
        user.phone=result.value("phone").toString().toStdString();
        win.id=result.value("win_id").toInt();
        int exam_id=result.value("exam_id").toInt();
        ud.getUser(user);
        wd.selectWindow(win);
        wins.push_back(win);
        users.push_back(user);
        exam_ids.push_back(exam_id);
    }

    return true;
}

//查询某个组织下的所有待审批的加盟申请对应的用户
bool ApproveExam::selectOrgJoin(OrganizationInfo org,vector<User>& users,vector<int> &exam_ids)
{
    //查询表joinApproval中org_id为查询条件，同时status为待审批状态,
    //获取用户id，以及对应的审批id
    //根据查出的所有用户id，调用userDao查询出用户完整信息，joinApprova表中user_id字段类型错了，应该是char(11)
    //所有查询结果返回

    UserDao db_user_dao;

    QString sql=("select * from joinApproval where organization_id = %1 and status = '%2';");
    sql=sql.arg(org.id).arg(ApproveExam::STATUS_EXAM);
    result=DataBase::getInstance()->exec(sql);

    while(result.next()) {
        exam_ids.push_back(result.value("id").toInt());

        User _user;
        _user.phone = result.value("user_id").toString().toStdString(); //把主键phone(相当于user_id),填入即可

        if(! db_user_dao.getUser(_user))
            return false;

        users.push_back(_user);
    }
    return true;
}

//查询某个组织下的所有审批申请成管理员的用户
bool ApproveExam::selectOrgAdmin(OrganizationInfo org,vector<User>& users)
{
    //这个不写
    Q_UNUSED(org);
    Q_UNUSED(users);
    return true;
}

//查询某个组织下的所有审批的菜品
bool ApproveExam::selectOrgExamFood(OrganizationInfo org,vector<SaleBase*>& sales)
{
    // 1.通过windowDao查出org对应的所有窗口vec_win_info
    WindowDao db_win_dao;
    vector<WindowInfo> vec_win_info = db_win_dao.selectOrgWindow(org);

    // 2.查询每个窗口对应的所有菜品（调用saleDao中的查询函数）
    SaleDao db_sale_dao;
    for(auto & i : vec_win_info)
    {
        vector<SaleBase *> vec_sale_info_p = db_sale_dao.selectAllSale(i);

        for(auto & j : vec_sale_info_p)
            // 3. 根据返回的菜品状态status，将status值为STATUS_exam（审批中）的菜品挑选出来返回
            if(j->status == SaleBase::STATUS_exam)
                sales.push_back(j);
    }

    return true;

}

//加盟审批查询，根据exam_id查询，返回组织id和userid
bool ApproveExam::selectExam(int exam_id,int& org_id,int& user_id)
{
    //查询表joinApproval返回值
    QString sql=("select * from joinApproval where id = %1;");
    sql=sql.arg(exam_id);
    result=DataBase::getInstance()->exec(sql);

    result.next();
    org_id = result.value("organization_id").toInt();
    user_id = result.value("user_id").toInt();

    return true;
}

//加盟审批状态修改
bool ApproveExam::alterJionExam(int exam_id,int status)
{
    //操作表joinApproval，根据exam_id查询出结果
    //更改status的值
    //managerController中的加盟审批函数examJoin需要完善，这里只做数据操作，不做逻辑处理
    //
    if(status != ApproveExam::STATUS_NOTPASS && status != ApproveExam::STATU_PASS && status != ApproveExam::STATUS_EXAM)
        return false;

    //更改joinApproval表的 status字段
    QString sql="update joinApproval set status = '%1' where id= %2;";
    sql=sql.arg(status).arg(exam_id);
    if(!result.exec(sql))
    {
        qDebug()<<result.lastError().text();
        return false;
    }

    return true;

}

//加盟申请
bool ApproveExam::addJionExam(User user,OrganizationInfo org)
{
    //对表joinApproval进行插入操作，插入新的审批
    /* id 自动生成，status自动生成为2
     * userid就是用户的手机号
     *
     * */
    if(user.type == User::TYPE_administrator){
        QString sql="insert into joinApproval(user_id,organization_id,status) value(%1,%2,'%3');";
        sql=sql.arg(QString::fromStdString(user.phone)).arg(org.id).arg(1);
        if(result.exec(sql))
            return true;
        else{
            qDebug()<<result.lastError().text();
            return false;
        }
    }
    else{
        QString sql="insert into joinApproval(user_id,organization_id) value(%1,%2);";
        sql=sql.arg(QString::fromStdString(user.phone)).arg(org.id);

        if(result.exec(sql))
            return true;
        else{
            qDebug()<<result.lastError().text();
            return false;
        }
    }
}

//窗口申请添加
bool ApproveExam::addWindowExam(User user,WindowInfo win)
{
    //对表windowApproval进行插入
    /* status自动生成为2
     * */

    QString sql="insert into windowApprova(user_id,window_id) value(%1,%2);";
    sql=sql.arg(QString::fromStdString(user.phone)).arg(win.id);

    if(result.exec(sql))
        return true;
    else{
        qDebug()<<result.lastError().text();
        return false;
    }
}

//窗口修改
bool ApproveExam::alterWindowExam(int exam_id ,int status)
{
    if(status != ApproveExam::STATUS_NOTPASS && status != ApproveExam::STATU_PASS && status != ApproveExam::STATUS_EXAM)
        return false;

    //更改windowApproval表的 status字段
    QString sql="update windowApproval set status = '%1' where id= %2;";
    sql=sql.arg(status).arg(exam_id);
    if(!result.exec(sql))
    {
        qDebug()<<result.lastError().text();
        return false;
    }

    return true;

}


//CREATE TABLE `joinApproval` (
//`id` int(255) NOT NULL,
//`organization_id` int(255) NOT NULL,
//`user_id` char(11) NOT NULL,
//`status` int(255) NOT NULL,
//PRIMARY KEY (`id`) USING BTREE
//) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;


//CREATE TABLE `windowApproval` (
//`window_id` int(255) NOT NULL,
//`user_id` char(11) NOT NULL,
//`id` int(255) NOT NULL,
//`status` int(255) NOT NULL,
//PRIMARY KEY (`id`) USING BTREE
//) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
